package com.ruoyi.erp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import org.springframework.stereotype.Service;
import com.ruoyi.common.core.mybatisplus.core.ServicePlusImpl;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.erp.domain.bo.RelateUnitTypeBo;
import com.ruoyi.erp.domain.vo.RelateUnitTypeVo;
import com.ruoyi.erp.domain.RelateUnitType;
import com.ruoyi.erp.mapper.RelateUnitTypeMapper;
import com.ruoyi.erp.service.IRelateUnitTypeService;

import java.util.List;
import java.util.Collection;

/**
 * 往来单位类型Service业务层处理
 *
 * @author chenyun
 * @date 2022-03-06
 */
@Service
public class RelateUnitTypeServiceImpl extends ServicePlusImpl<RelateUnitTypeMapper, RelateUnitType, RelateUnitTypeVo> implements IRelateUnitTypeService {
    private static final String UNIQUE_KEY = "relate_type_code";
    private static final String LOCK_KEY = "RelateUnitType:relate_type_code";
    @Override
    public RelateUnitTypeVo queryById(Long id){
        return getVoById(id);
    }


    @Override
    public List<RelateUnitTypeVo> queryList(RelateUnitTypeBo bo) {
        LambdaQueryWrapper<RelateUnitType> lqw = buildQueryWrapper(bo);
        return listVo(lqw);
    }

    @Override
    public Boolean insertByBo(RelateUnitTypeBo bo) throws Exception{
        RelateUnitType add = BeanUtil.toBean(bo, RelateUnitType.class);
        validEntityBeforeSave(add);
        QueryWrapper wrapper = existQueryWrapper(add);
        boolean flag = insertIdempotency(add,LOCK_KEY,wrapper,getMsg(add));
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    @Override
    public Boolean updateByBo(RelateUnitTypeBo bo) throws Exception{
        RelateUnitType update = BeanUtil.toBean(bo, RelateUnitType.class);
        validEntityBeforeSave(update);
        QueryWrapper wrapper = existQueryWrapper(update);
        boolean flag = updateIdempotency(update,LOCK_KEY,wrapper,getMsg(update));
        return flag;
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(RelateUnitType entity){
        //TODO 做一些数据校验,如唯一约束
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return removeByIds(ids);
    }

    /**
     * 唯一判断查询条件，暂支持一个键
     * @param entity
     * @return
     */
    private QueryWrapper<RelateUnitType> existQueryWrapper(RelateUnitType entity) {
        return new QueryWrapper<RelateUnitType>().eq(UNIQUE_KEY, entity.getRelateTypeCode());
    }

    private String getMsg(RelateUnitType entity){
            String unique = String.valueOf(entity.getRelateTypeCode());
            return "分类编码["+unique+"]已存在";
    }
}
